window.addEventListener("load", async () => {
  addExportButton();
  addInputBox();
  
  document.getElementById("exportBtn").addEventListener("click", () => {
    const el = createStatusElement();
    const page = document.getElementById("inputBox")?.value;
    
    if (!page || typeof Number(page) !== 'number' || Number(page) > 100) {
      alert("欢姐,请输入提取页数,最多只能输入100");
    } else {
      extractAllData(el, page);
    }
  });
});

// 提取所有数据
async function extractAllData(ele, count) {
  let data = []; // 清空全局数据
  const dom = document.getElementById("exportBtn")
  dom.disabled = true;
  for (let i = 0; i < count; i++) {
    ele.textContent = `✅ 正在提取数据中...,第 ${i + 1} 页数据已提取`;
    const pageData = extractProductInfo();
    data.push(...pageData); // 累积数据
    // console.log(`第 ${i + 1} 页数据已提取`, pageData);

    const nextPageBtn = document.getElementsByClassName("next-next")[1];
    if (!nextPageBtn) break; // 没有下一页按钮时退出循环

    nextPageBtn.click(); // 点击下一页
    await waitForPageLoad(); // 等待页面加载
  }
  data.disabled = false;
  ele.textContent = "✅ 提取成功...";
  console.log(`✅ 提取成功 ✅,以下是 ${count} 页数据总和:`, data);
  copyDataToClipboard(data, ele);
  // exportToCSVWithLinks(data, "商品信息.csv");
}

// 等待页面加载完成（模拟异步等待）
function waitForPageLoad() {
  return new Promise((resolve) => {
    setTimeout(resolve, 3000); // 等待 3 秒（根据实际加载时间调整）
  });
}
// 导出表格
function exportToCSVWithLinks(data, filename) {
  const header = ["SPM 活动 ID", "图片", "商品标题"];
  const rows = data.map((item) => [
    item.spmActId,
    `=HYPERLINK("${item.imgSrc}", "查看图片")`, // Excel 超链接公式
    item.title,
  ]);

  const csvContent =
    "\uFEFF" + [header, ...rows].map((row) => row.join(",")).join("\n");

  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
  const link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = filename;
  link.click();
}
// 提取商品信息
function extractProductInfo() {
  const wrapper = document.getElementById("content_items_wrapper");
  if (!wrapper) return [];

  const result = [];
  const productItems = wrapper.querySelectorAll(".tbpc-col");

  productItems.forEach((item) => {
    const aTag = item.querySelector("a[data-spm-act-id]");
    if (!aTag) return;

    const spmActId = aTag.getAttribute("data-spm-act-id");

    // 查找图片
    const mainPicWrapper = item.querySelector(".mainPicAdaptWrapper--V_ayd2hD");
    const imgTag = mainPicWrapper
      ? mainPicWrapper.querySelector("img.mainPic--Ds3X7I8z")
      : null;
    const imgSrc = imgTag ? imgTag.getAttribute("src") : "";

    // 查找标题
    const titleWrapper = item.querySelector(".title--qJ7Xg_90");
    const title = titleWrapper ? titleWrapper.textContent.trim() : "";

    // 备用图片查找
    let finalImgSrc = imgSrc;
    if (!finalImgSrc) {
      const fallbackImg = item.querySelector("img.mainImg--sPh_U37m");
      finalImgSrc = fallbackImg ? fallbackImg.getAttribute("src") : "";
    }

    // 补全相对路径（如果需要）
    if (finalImgSrc && finalImgSrc.startsWith("//")) {
      finalImgSrc = "https:" + finalImgSrc;
    }

    result.push({
      spmActId: spmActId,
      imgSrc: finalImgSrc,
      title: title,
    });
  });
  return result;
}
// 创建状态提示元素
function createStatusElement() {
  const el = document.createElement("div");
  el.id = "status";
  el.style.cssText = `
    position: fixed;
    top: 100px;
    right: 100px;
    z-index: 9999;
    background: #333;
    color: #fff;
    color: white;
    padding: 10px;
    border-radius: 4px;
    font-size: 20px;
  `;
  document.body.appendChild(el);
  return el;
}
// 添加导出按钮
function addExportButton() {
  if (document.getElementById("exportBtn")) return;

  const btn = document.createElement("button");
  btn.id = "exportBtn";
  btn.textContent = "数据提取";
  btn.style.cssText = `
    position: fixed;
    top: 50px;
    right: 50px;
    z-index: 9999;
    padding: 10px 15px;
    background: #007cba;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
  `;
  document.body.appendChild(btn);
}

// 复制到剪贴板
function copyDataToClipboard(data, ele) {
  try {
    ele.textContent = ele.textContent + "，已复制到剪贴板！！！";
    const jsonData = JSON.stringify(data, null, 2); // 格式化 JSON
    navigator.clipboard.writeText(jsonData);
    setTimeout(() => {
      ele.style.display = "none";
    }, 10000);
    // alert("数据已复制到剪贴板！");
  } catch (error) {
    alert("复制失败，请手动复制数据。");
    console.error("复制错误:", error);
  }
}

// 添加input框
function addInputBox() {
  if (document.getElementById("inputBox")) return;

  const input = document.createElement("input");
  input.id = "inputBox";
  input.type = "text";
  input.placeholder = "请输入数据提取页数";
  input.style.cssText = `
    position: fixed;
    top: 49px;
    right: 140px;
    z-index: 9999;
    padding: 10px;
    border-radius: 4px;
    font-size: 14px;
  `;
  document.body.appendChild(input);
}
